package com.jjzy;

import com.jjzy.realm.MyRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * Author:   wj
 * Date:     2020/2/7 18:03
 * Description: 自定义realm认证
 */
public class MainDemo {
    private static final transient Logger log = LoggerFactory.getLogger(MainDemo.class);
    public static void main(String[] args) {
        //创建subject
        String username = "1";
        String password = "123456";
        log.info("自定义realm实现认证");

        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        DefaultSecurityManager instance = (DefaultSecurityManager) factory.getInstance();
        //将自定义realm 绑定到安全管理器
        MyRealm myRealm = new MyRealm();
        instance.setRealm(myRealm);
        SecurityUtils.setSecurityManager(instance);
        Subject subject = SecurityUtils.getSubject();


        AuthenticationToken token = new UsernamePasswordToken(username, password);



        //做认证
        //得到认证
        try {
            subject.login(token);
            log.info("认证成功");
        } catch (AuthenticationException e) {
            log.error("认证失败");
        }

        //授权
        //判断是否拥有某个角色
        log.info("授权测试--------------");
        boolean hasRole = subject.hasRole("role1");
        System.out.println("拥有role1"+hasRole);
        System.out.println("hasRole = " + hasRole);

        //判断 是否 分别 拥有组里面的角色
        boolean[] hasRoles = subject.hasRoles(Arrays.asList("role1", "role2", "role3"));

        for (int i = 0; i < hasRoles.length; i++) {
            System.out.println("是否拥有"+hasRoles[i]);
        }
        //判断 是否拥有组里面的全部角色
        boolean hasAllRoles = subject.hasAllRoles(Arrays.asList("role1", "role2", "role3"));
        System.out.println(hasAllRoles);

        //判断是否拥有权限
        boolean permitted = subject.isPermitted("user:add");
        System.out.println(permitted);

        //判断是否拥有权限组
        boolean[] permitted1 = subject.isPermitted("user:add", "user:query");
        for (int i = 0; i <permitted1.length ; i++) {
            System.out.println(permitted1[i]);
        }

    }
}
